package org.zlb.netty.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class ProtobufUtil {
    
    public static void main(String[] args) {
        String toolPath = "D:/Program Files/protoc-3.9.2-win64/bin/protoc.exe";
        String input = "D:/_git/netty-study/doc";
        String output = "D:/_git/netty-study/src/main/java";
        String fileName = "SubReq.proto SubResp.proto";
        
        generate(toolPath, input, output, fileName);
    }
    
    public static void generate(String toolPath, String input, String output, String fileName) {
        StringBuffer strb = new StringBuffer();
        strb.append(toolPath)
                    .append(" --proto_path=")
                    .append(input)
                    .append(" --java_out=")
                    .append(output)
                    .append(" ")
                    .append(fileName);
        String cmd = strb.toString();
        
        StringBuilder stringBuilder = new StringBuilder();

        try {
            Process process = Runtime.getRuntime().exec(cmd);
            final InputStream is1 = process.getInputStream();
            new Thread(new Runnable() {
                public void run() {
                    BufferedReader bufferedReader = null;
                    String line = null;
                    try {
                        bufferedReader = new BufferedReader(
                                new InputStreamReader(is1, "GBK"));
                        while((line=bufferedReader.readLine()) != null) 
                        {
                            stringBuilder.append(line+"\n");
                        }
                        is1.close();
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }).start(); // 启动单独的线程来清空p.getInputStream()的缓冲区
            InputStream is2 = process.getErrorStream();
            BufferedReader br2 = new BufferedReader(new InputStreamReader(is2)); 
            StringBuilder buf = new StringBuilder(); // 保存输出结果流
            String line2 = null;
            while((line2 = br2.readLine()) != null) buf.append(line2); // 
            System.out.println(stringBuilder + "&" + buf);
        } catch (IOException e) {
             e.printStackTrace();
        }
    }
}
